package com.my.login.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

        Enumeration<String> attrs = session.getAttributeNames();

        // 读取Session中所有的键值对
        while (attrs.hasMoreElements()) {
            String key = attrs.nextElement().toString();
            Object value = session.getAttribute(key);
            System.out.println("------" + key + ":" + value + "--------\n");
        }

        System.out.println("===============>>>>>>当前uri：" + request.getRequestURI());

        // 匹配用户名密码的键值对（一般都是存放好的）
        Object sessionUsername = session.getAttribute("username");
        Object sessionPassword = session.getAttribute("password");

        System.out.println("=================>>>>>username:" + sessionUsername);
        if (sessionUsername == null || sessionPassword == null) {
            // Session为空有两种情况，一种是第一次登录，一种是Session失效
            String requestUsername = request.getParameter("username");
            String requestPassword = request.getParameter("password");
            if ("admin".equals(requestUsername) && "admin".equals(requestPassword)) {
                session.setAttribute("username", requestUsername);
                session.setAttribute("password", requestPassword);
                System.out.println("第一次登陆，放行请求");
                // 已登录，放行
                return true;
            }
            // Session失效的时候（即使存到Redis也需要设置失效时间的）肯定读取不到request的值，需要重新登陆
            System.out.println("未登录，请登录");
            response.sendRedirect(request.getContextPath() + "/toLogin");
            return false;
        } else if ("admin".equals(sessionUsername) && "admin".equals(sessionPassword)) {
            System.out.println("Session存在该用户记录，放行请求");
            return true;
        } else {
            System.out.println("请检查用户或密码");
            response.sendRedirect(request.getContextPath() + "/toLogin");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
